package com.sophie.chapter1;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

// import org.apache.kafka.common.serialization.StringSerializer;
public class ProducerFastStart {
    private static final String brokerList = "localhost:9092";

    private static final String topic = "heima";

    public static void main(String[] args) {
        Properties properties = new Properties();

        // 设置KEY序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        // properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        // 设置重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);

        // 设置值序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        // properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        // 设置集群地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
        // properties.put("bootstrap.servers", brokerList);

        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);
        // 发送消息对象
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, "kafka-hello-000", "hello, kafka!");
        ProducerRecord<String, String> record2 = new ProducerRecord<>(topic, 0, System.currentTimeMillis() - 10 * 500, "kafka-hello-002", "hello, kafka!>超时");
        try {
            // 发送消息
            producer.send(record);
            producer.send(record2);


            // 同步发送消息
            // Future<RecordMetadata> send = producer.send(record);
            // RecordMetadata recordMetadata = send.get();
            // System.out.println("topic=" + recordMetadata.topic());
            // System.out.println("partition=" + recordMetadata.partition());
            // System.out.println("offset=" + recordMetadata.offset());

            // 异步发送
            producer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e == null) {
                        System.out.println("topic=" + recordMetadata.topic());
                        System.out.println("partition=" + recordMetadata.partition());
                        System.out.println("offset=" + recordMetadata.offset());
                    }
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
        producer.close();
    }

}
